package com.shiguiwu.springmybatis.algorithm.queue;

/**
 * @description: 数组环形队列
 * @author: stone
 * @date: Created by 2021/3/1 14:54
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.queue
 */
public class CircleArrayQueue {

    //最大
    private int maxSize;
    //队尾的下一个位置
    private int rear;

    //队列头部
    private int front;

    //队列
    private int[] array;

    CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.array = new int[maxSize];
        this.rear = 0;
        this.front = 0;
    }

    //是否满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }


    //判断队列是否为空
    public boolean isEmpty() {
        return rear == front;
    }

    //加入队列
    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("队列已满，不能加入队列~~~");
            throw new RuntimeException("队列已满，不能加入队列~~~");
        }
        array[rear] = n;
        //将rear后移,这里必须考虑取模
        rear = (rear + 1) % maxSize;

    }

    //q取队列数据

    /**
     * 1,先把front保存到临时变量
     * 2,然后front后移，考虑取模
     * 3,将变量返回
     * @return
     */
    public int getQueue() {
        if (isEmpty()) {
            System.out.println("队列为空，不能出队~~~");
            throw new RuntimeException("队列为空，不能出队~~~");
        }
        int val = array[front];
        front = (front + 1) % maxSize;
        return val;

    }

    //打印
    public void print() {
        if (isEmpty()) {
            System.out.println("队列是空，没有数据~~~");
            return;
        }
        int length = size() + front;
        for (int i = front; i < length; i++) {
            System.out.printf("array[%d] = %d\n", i % maxSize, array[i % maxSize]);
        }
    }

    //有效个数
    public int size() {
        return (rear - front + maxSize) % maxSize;
    }

    //查询头部队列
    public int headQueue() {
        if (isEmpty()) {
            System.out.println("队列为空，没有头部~~~");
            throw new RuntimeException("队列为空，没有头部~~~");
        }
        return array[front];
    }
}
